package com.company.greedy;

import java.util.Stack;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/remove-duplicate-letters/
 * @date 2019/11/29 13:46
 * 给定一个仅包含小写字母的字符串，去除字符串中重复的字母，使得每个字母只出现一次。需保证返回结果的字典序最小（要求不能打乱其他字符的相对位置）。
 *
 * 示例 1:
 *  输入: "bcabc"
 *  输出: "abc"
 *  abc
 * 示例 2:
 *  输入: "cbacdcbc" cb } cdcbc
 *  输出: "acdb"
 *  acdb
 */
public class RemoveDuplicateLetters {

    public static void main(String[] args) {
        System.out.println(new RemoveDuplicateLetters().removeDuplicateLetters(""));
    }

    // 利用栈来完成
    public String removeDuplicateLetters(String s) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (stack.contains(c)) continue;

            while ((!stack.isEmpty() && stack.peek() > c) && s.indexOf(stack.peek(),i) != -1) {
                stack.pop();
            }
            stack.push(c);
        }

        char[] c = new char[stack.size()];

        for (int i = 0; i < stack.size(); i++) {
            c[i] = stack.get(i);
        }

        return new String(c);
    }

}
